package com.slz3.business.module.socialManagement.socArticle.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.goodsManagement.gooGoods.domain.GooGoods;
import com.slz3.business.module.socialManagement.socArticle.domain.SocArticle;
import com.slz3.business.module.socialManagement.socArticle.domain.SocArticleFactory;
import com.slz3.business.module.socialManagement.socArticle.steward.SocArticleSpecification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SocArticleServiceImpl implements SocArticleService {
    @Override
    public SocArticle save(SocArticle socArticle) {
        return Repositorys.socArticle.save(SocArticleFactory.initBaseFields(socArticle));
    }

    @Override
    public Page<SocArticle> page(MultiValueMap<String, String> params) {
        Page<SocArticle> socArticlePage = Repositorys.socArticle.findAll(
                SocArticleSpecification.findJoin(params), PageableSteward.extract(params)
        );
        // join
        Map<UUID, GooGoods> gooGoodsMap = Repositorys.gooGoods.findAllById(
                socArticlePage.getContent().stream()
                        .filter(item -> item.getFkGoods() != null)
                        .map(SocArticle::getFkGoods)
                        .collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(GooGoods::getUuid, Function.identity()));
        // merge
        socArticlePage.getContent().stream().forEach(item -> item.setGooGoods(gooGoodsMap.get(item.getFkGoods())));
        return socArticlePage;
    }


    @Override
    public SocArticle modify(SocArticle socArticleNew) {
        return Repositorys.socArticle.saveAndFlush(SocArticleFactory.initBaseFields(socArticleNew));
    }

    @Override
    public Optional<SocArticle> single(UUID uuid) {
        return Repositorys.socArticle.findById(uuid);
    }

    @Override
    public List<SocArticle> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.socArticle.findAllById(uuids);
    }

    @Override
    public List<SocArticle> delete(List<SocArticle> socArticleList) {
        socArticleList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            SocArticleFactory.initBaseFields(item);
        });
        return Services.socArticleTransactional.batchModify(socArticleList);
    }

}
